package com.ccp.dev.system.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.annotion.ActionExecOrder;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.system.consts.FileManagementContants;
import com.ccp.dev.system.model.GlobalType;
import com.ccp.dev.system.model.SysFile;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.system.service.SysFileService;
import com.ccp.dev.system.service.SysTypeKeyService;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SYS_FILE 控制器类
 *
 * @author zhaowj
 */
@Controller
@Action(ownermodel = SysAuditModelType.SYSTEM_SETTING)
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_SYSTEM + "/attachFile")
public class SysFileController extends SysBaseController {

    @Resource
    private SysFileService sysFileService;
    @Resource
    private SysTypeKeyService sysTypeKeyService;

    /**
     * 附件上传操作
     *
     * @param request 请求
     * @return 上传结果
     */
    @PostMapping("/fileUpload")
    @Action(description = "附件上传", execOrder=ActionExecOrder.BEFORE,exectype = "上传日志",detail = "附件上传<#if success>成功<#else>失败</#if>")
    public void fileUpload(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        try {
            //文件分类
            String typeId = RequestUtil.getString(request, "typeId");
            //格式要求
            String fileFormat = RequestUtil.getString(request, "fileFormat");
            //20200515附件表增加密级字段file_level
            int fileLevel = RequestUtil.getInt(request, "fileLevel") == 0 ? FileManagementContants.FILE_SECRET_PUBLIC : RequestUtil.getInt(request, "fileLevel");
            Map<String, Object> result = sysFileService.fileUpload(request, typeId, fileFormat,fileLevel);
            JSONObject json = JSONObject.fromObject(getResultDataSuccess("file.upload.success", result));
            writer.print(json.toString());
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } catch (Exception e) {
            JSONObject json = JSONObject.fromObject(getResultDataError("file.upload.failure"));
            writer.print(json.toString());
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
    }

    /**
     * 富文本图片上传
     *
     * @param request 请求
     * @return 上传结果
     */
    @PostMapping("/uploadImage")
    @Action(description = "富文本图片上传",execOrder=ActionExecOrder.BEFORE, exectype = "上传日志",detail = "富文本图片上传<#if success>成功<#else>失败</#if>")
    public void uploadImage(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        try {
            //文件分类
            String typeId = RequestUtil.getString(request, "typeId");
            //格式要求
            String fileFormat = RequestUtil.getString(request, "fileFormat");
            //20200515附件表增加密级字段file_level 图片默认都是非密
            Map<String, Object> result = sysFileService.fileUpload(request, typeId, fileFormat,FileManagementContants.FILE_SECRET_PUBLIC);
            List<Map<String, Object>> dataList = (List<Map<String, Object>>) result.get("fileList");
            String fieldId = dataList.get(0).get("fileId").toString();
            Map<String, Object> retMap = new HashMap<>();
            //取得服务器IP
            String ip = RequestUtil.getIpAddr(request);
            if (ip.contains("0:0:0:0:0:0:0:1")) {
                ip = "localhost";
            }
            int port = request.getLocalPort();
            String ctxPath = request.getContextPath();
            String src = "http://" + ip + ":" + port + ctxPath + "/system/attachFile/getFileById?fileId=" + fieldId;
            retMap.put("src", src);
            JSONObject json = JSONObject.fromObject(getResultDataSuccess("file.upload.success", retMap));
            writer.print(json.toString());
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } catch (Exception e) {
            JSONObject json = JSONObject.fromObject(getResultDataError("file.upload.failure"));
            writer.print(json.toString());
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
    }

    /**
     * 附件下载
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     */
    @GetMapping("/download")
    @Action(description = "附件下载", exectype = "下载日志",
            detail = "<#assign entity=sysFileService.getOneById(fileId)/>下载附件【${entity.fileName}】<#if success>成功<#else>失败</#if>")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileId = RequestUtil.getString(request, "fileId");
        sysFileService.downloadFile(request, response, fileId);
        SysAuditThreadLocalHolder.putParamerter("success", true);
    }

    /**
     * 根据文件id取得附件数据
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     */
    @GetMapping("/getFileById")
    @Action(description = "获取文件流", exectype = "下载日志",
            detail = "<#assign entity=sysFileService.getOneById(fileId)/>获取附件【${entity.fileName}】流<#if success>成功<#else>失败</#if>")
    public void getFileById(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileId = RequestUtil.getString(request, "fileId");
        sysFileService.getFileInfo(response, fileId);
        SysAuditThreadLocalHolder.putParamerter("success", true);
    }

    /**
     * 删除附件。
     *
     * @param request HttpServletRequest
     */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description = "删除附件", exectype = "删除日志", detail = "删除系统附件<#if success>成功<#else>失败</#if>")
    public ResultData delByFileId(HttpServletRequest request) {
        String[] ids = RequestUtil.getStringAryByStr(request, "id");
        if (StringUtil.isEmpty(ids)) {
            return getResultDataError("delete.failure.message");
        }
        try {
            sysFileService.delFile(ids);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("delete.success");
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("delete.failure");
        }
    }


    /**
     * 取得附件分页列表
     *
     * @param request HttpServletRequest
     * @return model
     */
    @GetMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "查看附件分页列表", exectype = "查询日志", detail = "查看附件分页列表<#if success>失败<#else>成功</#if>")
    @ResponseBody
    public ResultData list(HttpServletRequest request) {
        try {
            QueryFilter filter = new QueryFilter(request);
            filter.addFilter("tenantId", ContextUtil.getCurrentUser().getTenantId());
            List<SysFile> list = sysFileService.queryList(filter);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success", filter.getPageBean().getTotalCount(), list);
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 根据主键查询信息
     *
     * @return model
     */
    @GetMapping(UrlConstants.MODULE_FUNCTION_GET)
    @Action(description = "查看附件详情页", exectype = "查询日志", detail = "查看附件<#if StringUtil.isNotEmpty(fileName)>${fileName}】</#if>详情页")
    @ResponseBody
    public ResultData get(String fileId) {
        SysFile sysFile = sysFileService.getOneById(fileId);
        if (BeanUtils.isNotEmpty(sysFile)) {
            SysAuditThreadLocalHolder.putParamerter("fileName", sysFile.getFileName());
        }
        return getResultDataSuccess("query.success", sysFile);
    }

    /**
     * 页面跳转 列表页
     */
    @Action(description = "附件列表页面跳转", exectype = "页面跳转日志")
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/list")
    public String viewList() {
        return "sysFile/list";
    }

    /**
     * 页面跳转 详情页
     */
    @Action(description = "附件详情页面跳转", exectype = "页面跳转日志")
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/get")
    public String viewGet(String fileId, ModelMap modelMap) {
        modelMap.put("fileId", fileId);
        return "sysFile/get";
    }

    /**
     * 附件选择器 跳转路径
     *
     * @return
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/selector")
    @Action(description = "附件选择器-弹窗跳转路径")
    public String viewSelector(HttpServletRequest request, Model model) {
        int isSingle = RequestUtil.getInt(request, "isSingle", 0);
        model.addAttribute("isSingle", isSingle);
        return "sysFile/selector";
    }

    /**
     * 附件选择器 获取数据列表
     *
     * @return
     */
    @RequestMapping("/selector")
    @Action(description = "附件选择器-获取数据列表")
    @ResponseBody
    public ResultData getSelector(HttpServletRequest request) {
        String typeId = RequestUtil.getString(request, "typeId");
        QueryFilter filter = new QueryFilter(request);

        String cateTypeId = sysTypeKeyService.getByKey(GlobalType.CAT_FILE).getTypeId();
        if (StringUtil.isNotEmpty(typeId) && !typeId.equals(cateTypeId)) {
            filter.addFilter("typeId", typeId);
        }
        SysUser user = (SysUser) ContextUtil.getCurrentUser();
        filter.addFilter("tenantId", ContextUtil.getCurrentUserTenantId());
        filter.addFilter("userId", user.getUserId());
        List<SysFile> list = sysFileService.queryFileAttch(filter);

        return getResultDataSuccess("query.success", filter.getPageBean().getTotalCount(), list);
    }

    /**
     * 上传附件-弹窗
     *
     * @return
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/importXml")
    @Action(description = "上传附件页面")
    public String viewImportXmlList(HttpServletRequest request, Model model) {
//        String typeId = RequestUtil.getString(request,"typeId");
//        model.addAttribute("typeId",typeId);
        return "sysFile/importXml";
    }
}
